﻿namespace K.Client
{
    public class ModuleBase
    {
        protected int beginID;
        protected int endID;

        protected delegate void MsgHandler(Msg msg);
        protected MsgHandler[] mMsgHandlers;
        public ModuleBase() { Init(); }

        protected virtual void Init() { }
        public virtual void Awake() { }
        public virtual void Start() { }
        public virtual void Update() { }

        public void OnMsg(Msg msg)
        {
            int nIndex = GetModuleHandlerIndex(msg.id);
            if (nIndex == -1) { return; }

            MsgHandler handler = mMsgHandlers[nIndex];
            if (null == handler)
            {
                DefaultHandler(msg);
            }
            else
            {
                handler(msg);
            }
        }

        protected void InitMsg(int nBeginID, int nEndID)
        {
            beginID = nBeginID; endID = nEndID;
            mMsgHandlers = new MsgHandler[endID - beginID];
        }

        protected void RegisterMsgHandler(int nMsgID, MsgHandler vHandler)
        {
            int nIndex = GetModuleHandlerIndex(nMsgID);
            mMsgHandlers[nIndex] = vHandler;
        }

        protected int GetModuleHandlerIndex(int nMsgID)
        {
            int handlerIndex = (nMsgID & 0x000FFF) - (beginID & 0x000FFF);
            bool IsValid = handlerIndex <= 0 || handlerIndex >= endID - beginID;
            return IsValid ? -1 : handlerIndex;
        }

        protected virtual void DefaultHandler(Msg msg) { }
    }
}